package zl.osimall.manager.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import zl.osimall.common.bean.Category;
import zl.osimall.common.bean.RespBean;
import zl.osimall.common.exception.SteduException;
import zl.osimall.common.service.CategoryService;

import java.util.List;

@RestController
@RequestMapping("/api/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Value("${zl.uploaddir}")
    public String uploaddir;


    @GetMapping("/page")
    public RespBean selectConditionByPage( Category condition,
                                          Integer pageNum, Integer pageSize) {
        Object result = null;
        if(pageNum != null){
            result = categoryService.selectByLike(condition, pageNum, pageSize);
        }else {
            result = categoryService.selectCondition(condition);
        }
        return RespBean.ok("查询成功", result);
    }

    @GetMapping
    public RespBean selectAllParent(){
        List<Category> allparent = categoryService.selectAllParent();
        return RespBean.ok("查询成功", allparent);
    }

    @GetMapping("/{id}")
    public RespBean selectById(@PathVariable("id") Integer id) throws SteduException{
        return RespBean.ok("查询成功", categoryService.selectById(id));
    }

    @PostMapping
    public RespBean add(@RequestBody  Category category) throws SteduException {
        if (category.getPic().isEmpty()){
            return RespBean.error("图片不能为空");
        }
        categoryService.add(category);
        return RespBean.ok("添加成功");
    }

    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id) throws SteduException {
        categoryService.delete(id);
        return RespBean.ok("删除成功");
    }

    @PutMapping
    public RespBean update(@RequestBody  Category category) throws SteduException {
        categoryService.update(category);
        return RespBean.ok("修改成功");
    }

    /*@PostMapping("/upload")
    public RespBean upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString().replace("-", "") + filename;
        file.transferTo(new File(uploaddir + filename));
        return RespBean.ok("上传成功",filename);
    }*/
}
